package com.laiketui.task.queue;

import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.utils.tool.DateUtil;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 消息体
 *
 * @author Trick
 * @date 2021/11/19 16:00
 */
public class Message implements Delayed {

    private int id;

    private String body;

    /**
     * 延迟时长 秒
     */
    private long executeTime;

    public Message(int id, String body, int executeTime) {
        this.id = id;
        this.body = body;
        this.executeTime = executeTime + DateUtil.getTime();
        ;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public long getExecuteTime() {
        return executeTime;
    }

    public void setExecuteTime(long executeTime) {
        this.executeTime = executeTime;
    }

    /**
     * 延迟任务是否到时就是按照这个方法判断如果返回的是负数则说明到期否则还没到期
     *
     * @param unit -
     * @return long
     * @throws LaiKeAPIException-
     * @author Trick
     * @date 2021/11/19 16:06
     */
    @Override
    public long getDelay(TimeUnit unit) throws LaiKeAPIException {
        return this.executeTime - DateUtil.getTime();
    }

    /**
     * 自定义实现比较方法返回 1 0 -1三个参数
     *
     * @param delayed -
     * @return long
     * @throws LaiKeAPIException-
     * @author Trick
     * @date 2021/11/19 16:06
     */
    @Override
    public int compareTo(Delayed delayed) throws LaiKeAPIException {
        Message msg = (Message) delayed;
        return Long.compare(this.executeTime, msg.getExecuteTime());
    }
}
